package com.xm.thread.wait2notify;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 方案2：使用BlockingQueue（生产者-消费者最佳实践）
 * 优势：
 *   自动处理线程阻塞/唤醒
 *   内置多种队列策略（有界/无界、公平/非公平）
 *   无需手动实现同步逻辑
 */
@Slf4j
public class WaitToNotify03 {
    int capacity = 10;
    BlockingQueue<Integer> queue = new LinkedBlockingDeque<>(capacity);

    //生产者
    Runnable producer = () -> {
        try {
            for (int i = 0; i < 15; i++) {
                if (i >= capacity) {
                    Thread.sleep(1000);
                    log.info("------------------");
                }
                log.info("Produced：{}", i);
                queue.put(i);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    };


    //消费者
    Runnable consumer = () -> {
        try {
            while (true) {
                Integer num = queue.take();
                log.info("Consumed: {}", num);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    };
}
